using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
using System.Diagnostics;


namespace AutoUpdate
{
    public partial class FrmLogin : Form
    {
        //private bool schimbatCoonString = true;
        public bool loadTabele = false;
        SqlConnection Conexiune = null;
      

        public Boolean InstaleazaSQL = false;
        public String CurrentConnectionString = String.Empty;
        public String ConnectionString = String.Empty;
        public FrmLogin(String conn,String instanta)
        {
            CurrentConnectionString = conn;
            InitializeComponent();
            if(instanta!=String.Empty)
                ctrlServer.Text = @".\" + instanta;
        }
        public void MyTrace(String val)
        {
            Trace.WriteLine("[" + DateTime.Now.ToString() + "]" + val);
        }        
        /// <summary>
        /// returneaza sirul de conectare introdus in controale
        /// </summary>
        /// <returns></returns>
        public String GetCtrlConnString(Boolean defaultB)
        {
            String numeBaza = "master";
           
            String conString = "Data Source=" + ctrlServer.Text + ";Initial Catalog=" + numeBaza + ";";
            if (radioButtonAuthWin.Checked == true)
                conString += "Integrated Security=True;";
            else
            {
                conString += "User ID=" + this.ctrlUtilizator.Text + ";";
                conString += "Password=" + this.ctrlParola.Text + ";";
            }
            switch (comboBoxNet.SelectedIndex)
            {
                case 1:
                    conString += "Net=dbmssocn;";
                    break;
                case 2:
                    conString += "Net=dbnmpntw;"; //pipe
                    break;
                case 0:
                    conString += "Net=dbmslpcn;";
                    break;
                case -1:
                    //daca nu a fost selectat nici un protocol merge pe TCP/IP
                    conString += "Net=dbmssocn;";
                    break;
            }
            conString += "Connection Timeout=" + numericUpDown1.Value.ToString() + ";";
            return conString;
        
        }

        
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            comboBoxNet.SelectedIndex = 1;
            //System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe"); 
                       
            ////MyTrace("1");
            //KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
            //if (configSettings["DefaultConnection"] == null)
            //{
            //    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DefaultConnection", "SallyConnectionString"));
            //    config.Save();
            //}

            ////MyTrace("2");
            //ConfigurationSection section = config.GetSection("connectionStrings");
            //if (section.SectionInformation.IsProtected)
            //{
            //    try
            //    {
            //        section.SectionInformation.UnprotectSection();
            //    }
            //    catch(Exception)
            //    {
            //        config.Sections.Remove("connectionStrings");
            //    }
            //}
            /////incarca combo cu numele conexiunilor
            /////
            //foreach (ConnectionStringSettings cs1 in config.ConnectionStrings.ConnectionStrings)
            //{
            //    this.ConexiuneCB.Items.Add(cs1.Name);
            //}
            ////MyTrace("3");
            ////if (configSettings["DefaultConnection"] != null)
            ////{
            ////    this.ConexiuneCB.Text = configSettings["DefaultConnection"].Value.ToString();
            ////    ConnectionString = configSettings[CurrentConnectionString].Value.ToString();
            ////}
            ////else
            ////{
            ////    MessageBox.Show("Nu s-a definit Default Connection", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            ////    return;
            ////}
            //if (CurrentConnectionString != String.Empty)
            //{
            //    this.ConexiuneCB.Text = CurrentConnectionString;
            //    ConnectionString = config.ConnectionStrings.ConnectionStrings[CurrentConnectionString].ToString();
            //}
            
         
        }

  
        /// <summary>
        /// VERIFICA DACA se poate face o conexiune la baza de date
        /// </summary>
        /// <returns></returns>
        bool Deschide()
        {  
            try
            {
                if (Conexiune != null)
                    Conexiune.Dispose();
                ConnectionString = GetCtrlConnString(false);
                Conexiune = new SqlConnection(ConnectionString);
                Conexiune.Open();
                Conexiune.Close();
                
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                Conexiune.Dispose();
            }
            
            return true;
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //this.Save();
            if (Deschide() == true)
            {
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void radioButtonAuthSQL_CheckedChanged(object sender, EventArgs e)
        {
            this.ctrlParola.Enabled = true;
            this.ctrlUtilizator.Enabled = true;
            this.linkLabelAltUtilizator.Enabled = false;
        }

        private void radioButtonAuthWin_CheckedChanged(object sender, EventArgs e)
        {
            this.ctrlParola.Enabled = false;
            this.ctrlUtilizator.Enabled = false;
            this.linkLabelAltUtilizator.Enabled = true ;
        }      

        private void ctrlServer_TextChanged(object sender, EventArgs e)
        {
            loadTabele = false;
        }

        private void ctrlUtilizator_TextChanged(object sender, EventArgs e)
        {
            loadTabele = false;
        }

        private void ctrlParola_TextChanged(object sender, EventArgs e)
        {
            loadTabele = false;
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void comboBoxNet_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void linkLabelAltUtilizator_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ////WindowsImpersonate
            //FrmWindowsLogin frm = new FrmWindowsLogin();
            //frm.ShowDialog();
        }

       

        private void ctrlServer_TextChanged_1(object sender, EventArgs e)
        {
            //schimbatCoonString = true;
           
        }

        private void AutentificareObligatoriecheckBox_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void ConexiunecomboBox_TextChanged(object sender, EventArgs e)
        {
            //System.Configuration.Configuration config =
            //                        ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");

            //KeyValueConfigurationCollection configSettings = config.AppSettings.Settings;
            //if (configSettings["DefaultConnection"] == null)
            //{
            //    config.AppSettings.Settings.Add(new KeyValueConfigurationElement("DefaultConnection", this.ConexiuneCB.Text));
            //}
            //configSettings["DefaultConnection"].Value = this.ConexiuneCB.Text;
            
            //config.Save();
        }

       
        private void button3_Click(object sender, EventArgs e)
        {
            //this.Save();
            if (!Deschide())
            {
                MessageBox.Show("Valori incorecte!\nConectare imposibila la baza de date!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
            
        }

        private void SQL_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            InstaleazaSQL = true;
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            Close();
        }

    }
}